<template>
	<view class="clone">
		<u-sticky bgColor="#ffffff" :customNavHeight="0" :offsetTop="0"
			style="top: 0; padding-top: 20rpx;">
			<u-tabs
          activeStyle="color:#ea4679;fontWeight:bold;fontSize:32rpx;"
          @change="tabsChange"
          :current="tabsCurrent" lineColor="#ea4679"
          :list="tabsList"
          :scrollable="false"
      ></u-tabs>
		</u-sticky>
		<view class="page-content">
			<view v-if="currentType === 'body'" class="title-wrap">
				<view class="title">{{ '我的形象(' + total + ')' }}</view>
				<view @tap="goCreate" class="btn">
					<text class="icon">+</text>
					<text class="text">新建</text>
				</view>
			</view>
			<view v-else-if="currentType === 'voice'" class="title-wrap">
				<view class="title">{{ '我的声音(' + total + ')' }}</view>
				<view @tap="goCreate" class="btn">
					<text class="icon">+</text>
					<text class="text">新建</text>
				</view>
			</view>
			<view class="list" v-if="currentType === 'body'">
				<view class="item" v-for="(item, index) in list" :key="index">
					<view @tap="goPlayVideo(item)" class="top">
						<image mode="aspectFill" :src="item.poster || ''"></image>
					</view>

					<view @tap="openBodyActions(item)" class="bottom" v-if="item.status === 1">
						<view class="name u-line-1">{{ item.title }}</view>
						<view class="more">
							<image mode="widthFix" src="/static/clone/more-v.png">
							</image>
						</view>
					</view>

					<view class="status-wrap" v-else>
						<view class="producing" v-if="item.status === 0">
							<image mode="widthFix" src="/static/clone/ing.png"></image>
							<view class="primary">训练中</view>
						</view>
						<view @tap.stop="showFailedMsg(item)" class="error" v-if="item.status === 2">
							<image mode="widthFix" src="/static/clone/error.png">
							</image>
							<view class="error">训练失败</view>
						</view>
					</view>
				</view>
			</view>
			<view class="voice-list" v-if="currentType === 'voice'">
				<view class="item" v-for="(item, index) in list" :key="index">
					<view @tap="soundPlay('play', item)" class="left">
						<image v-if="item.playing" class="music-icon" mode="widthFix" src="/static/clone/ic_audio_pause.png"></image>
						<image v-else class="music-icon" mode="widthFix" src="/static/clone/ic_audio_play.png"></image>
					</view>
					<view class="center">
						<view class="name u-line-1">{{ item.title }}</view>
						<view class="time-wrap">
							<u-tag :plain="true" size="mini" text="克隆中"
								type="warning" v-if="item.status === 0"></u-tag>
							<u-tag :plain="true" size="mini" text="克隆成功"
								type="success" v-if="item.status === 1"></u-tag>
							<u-tag :plain="true" size="mini" text="克隆失败"
								type="danger" v-if="item.status === 2"></u-tag>
						</view>
					</view>

					<view class="right">
						<view @tap.stop.prevent="openSoundActions(item)" class="more" v-if="item.status === 1">
							<image mode="widthFix" src="/static/clone/more.png"></image>
						</view>
						<view class="status" v-else>
							<text style="color: #ea4679" v-if="item.status === 0">克隆中</text>
							<text @tap.stop="showFailedMsg(item)" style="color: #ff0000" v-if="item.status === 2">克隆失败</text>
						</view>
					</view>
				</view>
			</view>
      <view class="loadmore">
        <u-empty v-if="isEmpty" icon="/static/ic_empty_list.png" text="暂无内容"></u-empty>
        <u-loadmore v-else :status="status"></u-loadmore>
      </view>
		</view>
		<u-modal :asyncClose="true" :show="renameShow" title="重命名">
			<view class="add-resource-content">
				<view class="add-resource-form">
					<u--input
						border="surround"
						placeholder="请输入名称" shape="circle" v-model="renameForm.title"
					></u--input>
				</view>
			</view>
			<view slot="confirmButton">
				<view class="modal-action">
					<button @tap="closeRename" class="cancel-btn btn" :plain="true">取消</button>
					<button @tap="renameConfirm" class="confirm-btn btn" :loading="renameConfirmLoading"loadingText="保存中">确定</button>
				</view>
			</view>
		</u-modal>
		<u-popup @close="closeFailedMsg" mode="center" round="30rpx" :safeAreaInsetBottom="false" :show="cutFailedShow">
			<view class="user-info">
				<view class="title">
					<text>提 示</text>
					<view class="del-icon" @tap="closeFailedMsg">
						<u-icon color="#999999" name="close" size="16"></u-icon>
					</view>
				</view>
				<view class="msg">{{ cutFailedMsg }}</view>
				<view @tap="delFailed" class="confirm">删除</view>
			</view>
		</u-popup>
    <customTabbar selected="clone"></customTabbar>
	</view>
</template>

<script>
import customTabbar from '@/components/customTabbar'
export default {
  components: { customTabbar },
	data() {
		return {
			tabsCurrent: 0,
			tabsList: [
				{
					name: '形象克隆',
					type: 'body'
				},
				{
					name: '声音克隆',
					type: 'voice'
				}
			],
			listParams: {
				limit: 12,
				page: 1
			},
			list: [],
			isEmpty: false,
			status: 'loading',
			renameShow: false,
			renameConfirmLoading: false,
			renameForm: {
				id: '',
				title: ''
			},
			currentSetItem: null,
			total: 0,
			audio: null,
			cutFailedShow: false,
			cutFailedMsg: '',
      loopStatusSI: 0
		};
	},
	onPullDownRefresh() {
		this.listParams.page = 1;
		this.getList(1);
		setTimeout(function() {
			uni.stopPullDownRefresh();
		}, 500);
	},
	onReachBottom() {
		if (this.status === 'loading') {
			this.listParams.page += 1;
			this.getList();
		}
	},
  onLoad(option) {
    if (option.type) {
      this.tabsList.forEach((item, index) => {
        if (item.type === option.type) {
          this.tabsCurrent = index
        }
      })
    }
    this.status = 'loading';
    this.getList(1);
  },
  onShow() {
    this.status = 'loading';
    this.getList();
  },
	onHide() {
		this.soundPlay('pause');
	},
  onUnload() {
    this.soundPlay('pause');
    this.stopLoopStatus()
  },
  beforeDestroy() {
    this.soundPlay('pause');
    this.stopLoopStatus()
  },
	computed: {
		currentType() {
			return this.tabsList[this.tabsCurrent].type;
		},
    apiList(name) {
      if (this.currentType === 'body') {
        return {
          getCloneList: '/userBody/getList',
          editCloneInfo: '/userBody/rename',
          delClone: '/userBody/del'
        };
      }
      if (this.currentType === 'voice') {
        return {
          getCloneList: '/userVoice/getList',
          editCloneInfo: '/userVoice/rename',
          delClone: '/userVoice/del'
        };
      }
    },
	},
	methods: {
		openSoundActions(item) {
      var that = this;
			this.soundPlay('pause');
			var btns = ['重命名', '删除'];
			// if (item.rest_times > 0) {
      //   btns.unshift('训练');
			// }
			uni.showActionSheet({
				itemList: btns,
				success: function(res) {
          that.currentSetItem = item;
					var tapIndex = res.tapIndex;
          if (tapIndex === 0) {
            that.renameForm.title = item.title;
            that.renameForm.id = item.id;
            that.renameShow = true
            return
          }
          if (tapIndex === 1) {
            uni.showModal({
              title: '温馨提示',
              content: '确认删除此声音吗？删除后不可恢复',
              confirmColor: '#ea4679',
              success: function(res) {
                if (res.confirm) {
                  that.delVoice(that.currentSetItem.id)
                }
              }
            });
          }
				}
			});
		},
    delFailed() {
      this.cutFailedShow = false;
      this.delVoice(this.currentSetItem.id)
    },
    showFailedMsg(item) {
      switch(this.currentType) {
        case 'body':
          this.cutFailedMsg = item.fail_reason || '数字分身创作失败了，点击下面按钮可删除失败的数据。'
          break;
        case 'voice':
          this.cutFailedMsg = item.fail_reason || '声音克隆失败了，点击下面按钮可删除失败的数据。'
          break;
      }
      this.currentSetItem = item;
      this.cutFailedShow = true;
    },
    closeFailedMsg() {
      this.cutFailedMsg = ''
      this.currentSetItem = null;
      this.cutFailedShow = false;
    },
    delVoice(id) {
      this.$util.request({
        url: this.apiList.delClone,
        data: {
          id: id
        },
        loadingText: '正在删除'
      }).then(res => {
        this.$util.message(res.message)
        this.list = [];
        this.listParams.page = 1;
        this.getList();
      })
    },
		soundPlay(action, audio) {
			if (this.audio) {
				try {
					this.audio.pause();
					this.audio.destroy();
					this.audio = null;
				} catch (err) {
					console.log('soundPlay', err);
				}
			}
      if (audio && audio.playing) {
        this.list.map(item => {
          item.playing = false;
        })
      } else {
        this.list.map(item => {
          item.playing = false;
        })
        if (action === 'play') {
          audio.playing = true
          this.audio = uni.createInnerAudioContext()
          this.audio.autoplay = true
          this.audio.src = audio.demo_url || audio.url
        }
      }
		},
		tabsChange(val) {
			this.soundPlay('pause');
			this.tabsCurrent = val.index;
			this.list = [];
			this.listParams.page = 1;
			this.getList();
		},
    // 启动状态轮询
    startLoopStatus() {
      this.stopLoopStatus()
      this.loopStatusSI = setInterval(() => {
        this.getListStatus()
      }, 5000)
    },
    // 停止状态轮询
    stopLoopStatus() {
      if (this.loopStatusSI) {
        clearInterval(this.loopStatusSI)
        this.loopStatusSI = 0
      }
    },
    getListStatus() {
      var ids = []
      this.list.forEach(item => {
        if (item.status === 0) {
          ids.push(item.id)
        }
      })
      if (ids.length > 0) {
        this.$util.request({
          url: '/userVoice/getStatusByIds',
          data: {
            ids: ids.join(',')
          },
          loading: false
        }).then(res => {
          res.data.forEach(item => {
            if (item.status !== 0) {
              for(var i = 0; i < this.list.length; i++) {
                if (this.list[i].id === item.id) {
                  this.list[i] = item
                }
              }
            }
          })
          this.$forceUpdate()
        })
      }
    },
		goEditSound(item) {
			var page = '/pages/clone/create-voice';
			if (item) {
        page += '?id=' + item.id + '&title=' + item.title;
			}
			uni.navigateTo({
				url: page,
				events: {
					created: function() {
						this.getList();
					}
				}
			});
		},
		goCreate() {
			this.soundPlay('pause');
			var url = '/pages/clone/create-body';
			if (this.currentType === 'voice') {
        url = '/pages/clone/create-voice'
			}
			uni.navigateTo({
				url: url,
				events: {
					created: function() {
						this.getList();
					}
				}
			});
		},
    closeRename() {
      this.renameShow = false
    },
		renameConfirm() {
      if (!this.renameForm.title) {
        this.$util.message('请填写名称')
        return
      }
      this.$util.request({
        url: this.apiList.editCloneInfo,
        data: {
          id: this.renameForm.id,
          title: this.renameForm.title
        },
        loadingText: '正在保存'
      }).then(res => {
        this.renameShow = false;
        this.$util.message(res.message)
        this.list.forEach(item => {
          if (item.id === this.renameForm.id) {
            item.title = this.renameForm.title;
          }
        });
      })
		},
    openBodyActions(item) {
			var that = this;
			uni.showActionSheet({
				itemList: ['重命名', '删除'],
				success: function(res) {
          that.currentSetItem = item;
          var tapIndex = res.tapIndex
          if (tapIndex === 0) {
            that.renameForm.title = item.title;
            that.renameForm.id = item.id;
            that.renameShow = true
            return
          }
          if (tapIndex === 1) {
            uni.showModal({
              title: '温馨提示',
              content: '确认删除此分身吗？删除后不可恢复',
              confirmColor: '#ea4679',
              success: function (ret) {
                if (ret.confirm) {
                  that.$util.request({
                    url: that.apiList.delClone,
                    data: {
                      id: item.id
                    }
                  }).then(res => {
                    that.$util.message(res.message)
                    that.getList()
                  })
                }
              }
            })
          }
				}
			});
		},
		goPlayVideo(item) {
			var that = this;
      uni.navigateTo({
        url: '/pages/common/video-play?video_url=' + item.url + '&poster=' + item.poster
      });
		},
		getList(isRefresh = 0) {
      this.soundPlay('pause');
      this.isEmpty = false;
      this.status = 'loading';
      if (isRefresh) {
        this.list = []
      }
      this.$util.request({
        url: this.apiList.getCloneList
      }).then(res => {
        this.list = res.data.list.map(item => {
          item.times = Math.floor(10 * Math.random()) + 1;
          return item;
        });
        if (this.currentType === 'voice') {
          this.list = this.list.map(item => {
            this.$set(item, 'playing', false);
            return item;
          });
        }
        this.total = res.data.total;
        this.isEmpty = (this.list.length === 0);
        this.status = 'nomore';
        if (this.currentType === 'voice') {
          this.startLoopStatus();
        } else {
          this.stopLoopStatus();
        }
      })
		}
	},
}
</script>
<style scoped>
	@import './index.css';
</style>
